<template>
  <BeTable
    class="asset-interaction-records"
    rowKey="id"
    :columns="columns"
    :pagination="{ pageSize: pageSize, total: total }"
    :scroll="{ x: '100%' }"
    :formSetting="{ fields: searchFields, showExpandButton: false, maxShowFields: 7 }"
    :rowSelection="_rowSelection"
    :beforeFetch="beforeFetch"
    :api="getAssetInteractionRecordsList"
  >
    <!-- <template #toolbar>
      <a-dropdown trigger="click">
        <BeButton type="primary">
          导出
          <DownOutlined />
        </BeButton>
        <template #overlay>
          <a-menu>
            <a-menu-item :disabled="selectedRowKeys.length <= 0" @click.stop="exportInterfaceListByChecked()">导出选中结果</a-menu-item>
            <a-menu-item @click.stop="exportInterfaceList()">导出查询结果</a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
      <BeButton class="create-btn" type="primary" @click="showBatchInput = true">导入</BeButton>
    </template>-->
    <!-- :api="getAssetInteractionRecordsList" -->
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'resultFlag'">
        <div class="result-flag">
          <span :class="['dot', record.resultFlag === '成功' ? 'status-success' : record.resultFlag == '失败' ? 'status-fail' : '']"></span>
          <span>{{ record.resultFlag }}</span>
        </div>
      </template>
      <template v-if="column.key === 'resourcePath'">
        <div class="resource-path">{{ record.resourcePath }}</div>
      </template>
    </template>
  </BeTable>
  <BatchInput v-model:open="showBatchInput" />
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { TableColumnsType } from 'ant-design-vue'

import { assetInteractionRecordsApi } from '@/api/asset-interaction-records'
import type { GetAssetInteractionParams, AssetInteractionRecords } from '@/api/asset-interaction-records/type'
import { DownOutlined } from '@ant-design/icons-vue'
import BatchInput from '@/views/interface-list/components/BatchInput.vue'
import { handleExport } from '@/utils'
import dayjs from 'dayjs'
defineOptions({ name: 'AssetInteractionRecords' })
const tableData = ref<AssetInteractionRecords[]>([])
const pageSize = ref(15)
const total = ref(0)
const showBatchInput = ref(false)
const searchParams = ref<GetAssetInteractionParams>({})

// 搜索字段
const searchFields = [
  { label: '涉敏类型', prop: 'what_log_remarksa5', component: 'Input', componentProps: { placeholder: '请输入', allowClear: true } },
  { label: '服务端IP', prop: 'whereto_dev_dip_str', component: 'Input', componentProps: { placeholder: '请输入', allowClear: true } },
  { label: '客户端IP', prop: 'wherefrom_dev_sip_str', component: 'Input', componentProps: { placeholder: '请输入', allowClear: true } },
  { label: '域名', prop: 'what_dev_app_domain', component: 'Input', componentProps: { placeholder: '请输入', allowClear: true } },
  { label: '资产路径', prop: 'what_dev_app_url', component: 'Input', componentProps: { placeholder: '请输入', allowClear: true } },
  { label: '时间', prop: 'when_op_datetime', component: 'RangePicker', componentProps: { allowClear: true, format: 'YYYY-MM-DD' } }
]

// 列定义
const columns: TableColumnsType = [
  { title: '涉敏类型', align: 'left', dataIndex: 'what_log_remarksa5', key: '(what_log_remarksa5', width: '10%' },
  { title: '服务端IP', dataIndex: 'whereto_dev_dip_str', key: 'whereto_dev_dip_str', width: '10%' },
  { title: '服务端端口', dataIndex: 'whereto_dev_dport', key: 'whereto_dev_dport', width: '10%' },
  { title: '涉敏个数', dataIndex: 'what_log_remarksa3', key: 'what_log_remarksa3', width: '8%' },
  {
    title: '涉敏内容',

    dataIndex: 'what_op_cont',
    key: 'what_op_cont',
    width: '10%'
  },
  { title: '时间', dataIndex: 'when_op_datetime', key: 'when_op_datetime', width: '10%' },
  { title: '客户端IP', dataIndex: 'wherefrom_dev_sip_str', key: 'wherefrom_dev_sip_str', width: '10%' },
  { title: '授权凭证（UA）', dataIndex: 'why_form_remarks', key: 'why_form_remarks', width: '8%' },
  { title: '域名', dataIndex: 'what_dev_app_domain', key: 'what_dev_app_domain', width: '8%' },
  { title: '资产路径', align: 'left', dataIndex: 'what_dev_app_url', key: 'what_dev_app_url', width: '10%' }
]

// 行选择
const selectedRowKeys = ref<(string | number)[]>([])
const _rowSelection = ref({
  selectedRowKeys,
  onChange: (keys: (string | number)[], _selectedRows: any) => {
    selectedRowKeys.value = keys
  }
})

// // 处理搜索前参数（BeTable 会传入 params）
const beforeFetch = (params: any) => {
  searchParams.value = params

  // 定义字段映射关系
  const fieldMapping: {
    [key: string]: { name: string; column: string }
  } = {
    what_log_remarksa5: { name: '涉敏类型', column: 'what_log_remarksa5' },
    whereto_dev_dip_str: { name: '服务端IP', column: 'whereto_dev_dip_str' },
    wherefrom_dev_sip_str: { name: '客户端IP', column: 'wherefrom_dev_sip_str' },
    what_dev_app_domain: { name: '域名', column: 'what_dev_app_domain' },
    when_op_datetime: { name: '时间', column: 'when_op_datetime' },
    what_dev_app_url: { name: '资产路径', column: 'what_dev_app_url' }
  }

  // 构造 conditions 数组
  const conditions = [
    {
      name: '主键',
      column: 'what_op_app_id',
      type: 'string',
      conditionValue: {
        value: 'api_sensitive_log'
      }
    }
  ]
  for (const [key, value] of Object.entries(params)) {
    if (value && fieldMapping[key]) {
      if (fieldMapping[key].column === 'when_op_datetime' && Array.isArray(value)) {
        conditions.push({
          name: fieldMapping[key].name,
          column: fieldMapping[key].column,
          type: 'datetime',
          conditionValue: {
            beginDateTime: dayjs(value[0]).format('YYYY-MM-DD') + ' 00:00:00',
            endDateTime: dayjs(value[1]).format('YYYY-MM-DD') + ' 23:59:59'
          } as any
        })
      } else {
        conditions.push({
          name: fieldMapping[key].name,
          column: fieldMapping[key].column,
          type: 'string',
          conditionValue: {
            value: Array.isArray(value) ? value.join(',') : value
          } as any
        })
      }
    }
  }
  let obj = {
    pageIndex: params.page + 1,
    pageSize: pageSize.value,
    conditions: conditions,
    sort: {
      field: [],
      type: ''
    },
    columns: [],
    pageSign: ''
  }

  return obj
}

// 获取接口列表
const getAssetInteractionRecordsList = async (params?: GetAssetInteractionParams) => {
  return assetInteractionRecordsApi.GetAssetInteractionRecordsList({ data: { ...params } })
}

// 导出选中结果
const exportInterfaceListByChecked = async () => {
  handleExport(assetInteractionRecordsApi.exportAssetInteractionRecordsList, '资产交互记录-导出选中结果.xlsx', '是否导出所选数据？', { ids: selectedRowKeys.value })
}

// 按查询条件导出
const exportInterfaceList = async () => {
  const params: any = { ...searchParams.value }
  delete params.page
  delete params.size
  handleExport(assetInteractionRecordsApi.exportAssetInteractionRecordsList, '资产交互记录-导出查询结果.xlsx', '是否导出所有查询结果？', params)
}
</script>

<style lang="scss" scoped>
.asset-interaction-records {
  // padding: 0 20px;
  // background-color: var(--color-white);
  .result-flag {
    .dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: #b1b1b3;
      display: inline-block;
      margin-right: 5px;
    }
    .status-success {
      background-color: var(--success);
    }
    .status-fail {
      background-color: var(--error);
    }
  }
  .resource-path {
    color: var(--primary);
  }
}
</style>
